//
//  AudioPlayerViewController.m
//  QDaily_Program
//
//  Created by dllo on 15/12/10.
//  Copyright © 2015年 WXCLegendary. All rights reserved.
//

#import "AudioPlayerViewController.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width / 375
#define HEIGTH [UIScreen mainScreen].bounds.size.height / 667
@interface AudioPlayerViewController ()
@property(nonatomic,strong)AVPlayer *player; // 播放属性
@property(nonatomic,strong)AVPlayerItem *playerItem; // 播放属性
@property(nonatomic,assign)CGFloat width; // 坐标
@property(nonatomic,assign)CGFloat height; // 坐标
@property(nonatomic,strong)UISlider *slider; // 进度条
@property(nonatomic,strong)UILabel *currentTimeLabel; // 当前播放时间
@property(nonatomic,strong)UILabel *systemTimeLabel; // 系统时间
@property(nonatomic,strong)UIView *backView; // 上面一层Viewd
@property(nonatomic,assign)CGPoint startPoint;
@property(nonatomic,assign)CGFloat systemVolume;
@property(nonatomic,strong)UISlider *volumeViewSlider;
@property(nonatomic,strong)UIActivityIndicatorView *activity; // 系统菊花
@property(nonatomic,strong)UIProgressView *progress; // 缓冲条
@property(nonatomic,strong)UIView *topView;

@end

@implementation AudioPlayerViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    _width = [[UIScreen mainScreen]bounds].size.height;
    _height = [[UIScreen mainScreen]bounds].size.width;
    // 创建AVPlayer
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.audioPlayerModel.mp4_url]];
    
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = CGRectMake(0, 0, _width, _height);
    // 全屏(有三个属性)/
    playerLayer.videoGravity = AVLayerVideoGravityResize;
    [self.view.layer addSublayer:playerLayer];
    [self.player play];
    
    //AVPlayer播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _width, _height)];
    [self.view addSubview:self.backView];
    self.backView.backgroundColor = [UIColor clearColor];
    
    self.topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _width, _height * 0.19)];
    _topView.backgroundColor = [UIColor blackColor];
    _topView.alpha = 0.5;
    [self.backView addSubview:_topView];
    
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    
    [self createProgress];
    [self createSlider];
    [self createCurrentTimeLabel];
    [self createButton];
    [self backButton];
    [self createTitle];
    [self createGesture];
    
    [self customVideoSlider];
    
    self.activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.activity.center = self.backView.center;
    [self.view addSubview:self.activity];
    [self.activity startAnimating];
    
    //    //延迟线程
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.backView.alpha = 0;
        }];
        
    });
    
    //计时器
    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(Stack) userInfo:nil repeats:YES];
    //    self.modalPresentationCapturesStatusBarAppearance = YES;
    
}


#pragma mark - 横屏代码
- (BOOL)shouldAutorotate{
    return NO;
} //NS_AVAILABLE_IOS(6_0);当前viewcontroller是否支持转屏

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return UIInterfaceOrientationMaskLandscape;
} //当前viewcontroller支持哪些转屏方向

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)prefersStatusBarHidden
{
    return NO; // 返回NO表示要显示，返回YES将hiden
}
#pragma mark - 创建UISlider
- (void)createSlider
{
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(100 * WIDTH, 345 * HEIGTH, _width * 0.7, 15 * HEIGTH)];
    [self.backView addSubview:self.slider];
    // 自定义圆圈
    [self.slider setThumbImage:[UIImage imageNamed:@"circle"] forState:UIControlStateNormal];
//    [_slider setMaximumTrackImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [_slider setMinimumTrackImage:[UIImage imageNamed:@"bat2"] forState:UIControlStateNormal];
    
    
    [self.slider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    // 播放完成的颜色
//    self.slider.minimumTrackTintColor = [UIColor colorWithRed:30 / 255.0 green:80 / 255.0 blue:100 / 255.0 alpha:1];
    
}

#pragma mark - slider滑动事件
- (void)progressSlider:(UISlider *)slider
{
    //拖动改变视频播放进度
    if (self.player.status == AVPlayerStatusReadyToPlay) {
        
        //    //计算出拖动的当前秒数
        CGFloat total = (CGFloat)self.playerItem.duration.value / self.playerItem.duration.timescale;
        
        //    NSLog(@"%f", total);
        
        NSInteger dragedSeconds = floorf(total * slider.value);
        
        //转换成CMTime才能给player来控制播放进度
        
        CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
        
        [self.player pause];
        
        [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finish){
            
            [self.player play];
            
        }];
        
    }
}
#pragma mark - 创建UIProgressView
- (void)createProgress
{
    self.progress = [[UIProgressView alloc]initWithFrame:CGRectMake(102 * WIDTH, 352 * HEIGTH, _width * 0.69, 15 * HEIGTH)];
    [self.backView addSubview:_progress];
}
#pragma mark - 缓冲
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        CMTime duration = self.playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.progress setProgress:timeInterval / totalDuration animated:NO];
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}
- (void)customVideoSlider {
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    [self.slider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

#pragma mark - 创建播放时间
- (void)createCurrentTimeLabel
{
    self.currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(_width *0.86, 342 * HEIGTH, 100 * WIDTH, 20 * HEIGTH)];
    [self.backView addSubview:self.currentTimeLabel];
    self.currentTimeLabel.textColor = [UIColor whiteColor];

    self.currentTimeLabel.font = [UIFont systemFontOfSize:12 * HEIGTH];
    self.currentTimeLabel.text = @"00:00/00:00";
    
    
}
#pragma mark - 计时器事件
- (void)Stack
{
    if (self.playerItem.duration.timescale != 0) {
        
        self.slider.maximumValue = 1;//音乐总共时长
        self.slider.value = CMTimeGetSeconds([self.playerItem currentTime]) / (self.playerItem.duration.value / self.playerItem.duration.timescale);//当前进度
        
        //当前时长进度progress
        NSInteger proMin = (NSInteger)CMTimeGetSeconds([self.player currentTime]) / 60;//当前秒
        NSInteger proSec = (NSInteger)CMTimeGetSeconds([self.player currentTime]) % 60;//当前分钟
        //duration 总时长
        
        NSInteger durMin = (NSInteger)self.playerItem.duration.value / self.playerItem.duration.timescale / 60;//总秒
        NSInteger durSec = (NSInteger)self.playerItem.duration.value / self.playerItem.duration.timescale % 60;//总分钟
        self.currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    }
    if (self.player.status == AVPlayerStatusReadyToPlay) {
        [self.activity stopAnimating];
    } else {
        [self.activity startAnimating];
    }
    
}
#pragma mark - 播放按钮
- (void)createButton
{
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.frame = CGRectMake(15 * HEIGTH, 337 * HEIGTH, 30 * HEIGTH, 30 * HEIGTH);
    [self.backView addSubview:startButton];
    // rate 1播放 0暂停
    if (self.player.rate == 1.0) {
        
        [startButton setBackgroundImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    } else {
        [startButton setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        
    }
    [startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    nextButton.frame = CGRectMake(60 * WIDTH, 340 * HEIGTH, 25 * WIDTH, 25 * HEIGTH);
//    [self.backView addSubview:nextButton];
//    [nextButton setBackgroundImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    
    
}
#pragma mark - 播放暂停按钮方法
- (void)startAction:(UIButton *)button
{
    if (button.selected) {
        [self.player play];
        [button setBackgroundImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        
    } else {
        [self.player pause];
        [button setBackgroundImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
        
    }
    button.selected =!button.selected;
    
}
#pragma mark - 返回按钮方法
- (void)backButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(15 * WIDTH, 25 * HEIGTH, 30 * WIDTH, 30 * HEIGTH);
    [button setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(590 * WIDTH, 25 * HEIGTH, 30 * WIDTH, 30 * HEIGTH);
    [shareButton setBackgroundImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    
    [_backView addSubview:button];
    [_backView addSubview:shareButton];
    [button addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [shareButton addTarget:self action:@selector(shareUrl) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark — 分享按键方法
//- (void)shareUrl {
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:@"507fcab25270157b37000010"
//                                      shareText:[NSString stringWithFormat:@"%@:%@", self.audioPlayerModel.title, self.audioPlayerModel.mp4_url]
//                                     shareImage:[UIImage imageNamed:@"icon.png"]
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToEmail,UMShareToDouban,nil]
//                                       delegate:self];
//}

#pragma mark - 创建标题
- (void)createTitle
{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(80 * WIDTH, 20 * HEIGTH, 250 * WIDTH, 30 * HEIGTH)];
    [self.backView addSubview:label];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = self.audioPlayerModel.title;
}
#pragma mark - 创建手势
- (void)createGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    //获取系统音量
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    self.volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            self.volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    self.systemVolume = self.volumeViewSlider.value;
}
#pragma mark - 轻拍方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    if (self.backView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            
            self.backView.alpha = 0;
        }];
    } else if (self.backView.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            
            self.backView.alpha = 1;
        }];
    }
    if (self.backView.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:0.5 animations:^{
                
                self.backView.alpha = 0;
            }];
            
        });
        
    }
}
#pragma mark - 滑动调整音量大小
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(event.allTouches.count == 1){
        //保存当前触摸的位置
        CGPoint point = [[touches anyObject] locationInView:self.view];
        self.startPoint = point;
    }
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    
    if(event.allTouches.count == 1){
        //计算位移
        CGPoint point = [[touches anyObject] locationInView:self.view];
        //        float dx = point.x - startPoint.x;
        float dy = point.y - self.startPoint.y;
        int index = (int)dy;
        if(index>0){
            if(index%5==0){//每10个像素声音减一格
                NSLog(@"%.2f",self.systemVolume);
                if(self.systemVolume>0.1){
                    self.systemVolume = self.systemVolume-0.05;
                    [self.volumeViewSlider setValue:self.systemVolume animated:YES];
                    [self.volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        }else{
            if(index%5==0){//每10个像素声音增加一格
                NSLog(@"+x ==%d",index);
                NSLog(@"%.2f",self.systemVolume);
                if(self.systemVolume>=0 && self.systemVolume<1){
                    self.systemVolume = self.systemVolume+0.05;
                    [self.volumeViewSlider setValue:self.systemVolume animated:YES];
                    [self.volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        }
        //亮度调节
        //        [UIScreen mainScreen].brightness = (float) dx/self.view.bounds.size.width;
    }
}


- (void)moviePlayDidEnd:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        //        [[NSNotificationCenter defaultCenter]postNotificationName:@"start" object:nil userInfo:nil];
        
    }];
    
    
    
}
- (void)backButtonAction
{
    [self.player pause];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"start" object:nil userInfo:nil];
        
        
    }];
}
















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
